<template>
  <div class="moduleView" ref="scrollEl">
    <!-- 内容部分 -->
    <div class="moduleView-bg">
      <!-- 导航 -->
      <NavBar
        :title="$t('pledge.rechargeTitle')"
        isTransparent
        :navScorllOffset="60"
        navScorllColor="#FFF"
        :scrollEl="scrollEl"
        isFixed
      />
      <!-- 内容 -->
      <div class="content">
        <!-- 标题 -->
        <div class="content-title">{{ $t("pledge.xzckje") }}</div>
        <!-- 充值列表 -->
        <div
          v-for="item in pageData.list"
          :key="item.id"
          class="content-item items-center"
          :class="{ 'content-item-select': item.isSelect }"
          @click="radioChannel(item)"
        >
          <div class="content-item-left items-center">
            <div class="content-item-left-box">
              <img
                v-if="item.taskType == 2 || item.taskType == 7"
                class="content-item-left-img"
                src="/image/pledge/czbg15-icon.svg"
              />
              <img
                v-else
                class="content-item-left-img"
                src="/image/pledge/czbg-icon.svg"
              />
              <div class="content-item-left-money">${{ item.cash }}</div>
              <div class="content-item-left-xzcz items-center">
                <div
                  class="content-item-left-xzcz-text"
                  :class="{
                    'content-item-left-xzcz-text-normal':
                      item.taskType != 2 && item.taskType != 7,
                  }"
                >
                  {{
                    $t(
                      item.taskType == 2 || item.taskType == 7
                        ? "pledge.firstCz"
                        : "pledge.xzCz"
                    )
                  }}
                </div>
              </div>
            </div>

            <div style="flex: 1; padding-right: 10px">
              <div class="content-item-left-title">
                <!-- <span></span> -->
                {{ item.description }}
              </div>
              <div class="content-item-left-rate items-center">
                <img
                  class="content-item-left-rate-img"
                  src="/image/pledge/income-icon.png"
                />
                <div class="content-item-left-rate-text">
                  +{{ decimalToLength(item.bonusProfitRate * 100, 1, true) }}%{{
                    $t("pledge.sylv")
                  }}
                </div>
              </div>
            </div>
          </div>
          <!-- 单选 -->
          <div
            class="content-item-right"
            :style="{
              border: item.isSelect ? '1px solid #ffb800' : '1px solid #d0d4df',
            }"
          >
            <p
              :style="{
                'background-color': item.isSelect ? '#ffb800' : 'transparent',
              }"
              class="content-item-right-center"
            ></p>
          </div>
        </div>

        <!-- 支付渠道 -->
        <div class="content-zfqd-title">{{ $t("pledge.xzfkfs") }}</div>
        <div class="content-zfqd-channel">
          <!-- 没有选择之前 -->
          <div
            v-if="!pageData.selectChannel"
            class="content-zfqd-channel-list items-center"
            @click="showChannelView(false)"
          >
            <div class="content-zfqd-channel-list-left items-center">
              <div v-for="(item, idx) in pageData.channels" :key="item.url">
                <div
                  v-if="idx < 5"
                  class="content-zfqd-channel-list-left-img"
                  :style="{ left: `${idx * -12}px` }"
                >
                  <Images isHttp :src="item.payImgUrl" />
                </div>
              </div>
              <div
                v-if="pageData.channels.length > 5"
                class="content-zfqd-channel-list-left-img"
                style="background-color: #fff; text-align: center"
                :style="{ left: `${5 * -12}px` }"
              >
                ...
              </div>
            </div>
            <div class="content-zfqd-channel-list-right items-center">
              {{ $t("pledge.gdfs") }}
              <img
                class="content-zfqd-channel-list-right-img"
                src="/image/pledge/right-icon.svg"
              />
            </div>
          </div>
          <!-- 选择以后的渠道显示 -->
          <div
            v-else
            class="content-zfqd-channel-select items-center"
            @click="showChannelView(true)"
          >
            <div class="content-zfqd-channel-list-left items-center">
              <div class="content-zfqd-channel-list-left-img">
                <Images isHttp :src="pageData.selectChannel.payImgUrl" />
              </div>
              <div class="content-zfqd-channel-list-left-title">
                {{ pageData.selectChannel.payName }}
              </div>
            </div>
            <div class="content-zfqd-channel-list-right items-center">
              <img
                class="content-zfqd-channel-list-right-img"
                src="/image/pledge/right-icon.svg"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 支付 -->
    <div class="footer items-center">
      <div class="footer-left">
        <div class="footer-left-money">${{ decimalToLength(cash) }}</div>
        <div class="footer-left-value">
          {{ pageData.selectChannel ? pageData.selectChannel.unit || "" : ""
          }}{{ exchange }}
        </div>
      </div>
      <div
        class="footer-right"
        :class="{
          'footer-right-disabled':
            !pageData.selectRecharge || !pageData.selectChannel,
        }"
        @click.stop="handleSubmit"
      >
        {{ $t("pledge.zfbtn") }}
      </div>
    </div>
  </div>
</template>
<script setup name="moduleView">
import { debounce, decimalToLength, navigateI18nTo, isiOS } from "@/utils";
import { getPledgeRechargeGear } from "@/api/pledge";
import { sendCommonMessage } from "@/api/log";
import { thirdPay, getPayEndSuccessID } from "@/api/pay";
import Decimal from "decimal.js";
import { useUserStore } from "~~/store/modules/user";
import { useGlobalStore } from "~~/store/global";
import * as MITO from "@zhj1214/qdjk-web";
import { usePageVisibility } from "@vant/use";
import { usePageCacheStore } from "../store/modules/pageCache";

const route = useRoute();
console.log("页面参数:", route.query);
const { t } = useI18n();

const scrollEl = ref();
// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase
// 用户信息
const userState = useUserStore();
const globalStore = useGlobalStore();
const pageCache = usePageCacheStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}
// 页面属性
const pageData = reactive({
  channels: [], // 渠道列表
  selectChannel: null, // 选择的渠道信息
  list: [], // 充值列表
  selectRecharge: null, // 选择的充值金额
});

// 充值金额:可能会随着选择的渠道不同而变化
const cash = computed(() => {
  if (pageData.selectRecharge) {
    return pageData.selectRecharge.cash;
  }
  return 0;
});

// 兑换外币
const exchange = computed(() => {
  if (pageData.selectChannel && pageData.selectRecharge) {
    if (pageData.selectChannel.currency) {
      return decimalToLength(
        new Decimal(pageData.selectChannel.currency)
          .mul(new Decimal(pageData.selectRecharge.cash))
          .toNumber()
      );
    }
  }
  return 0;
});

// 获取请求列表
const getPledgeRechargeGearRequest = (call) => {
  getPledgeRechargeGear({
    cache: !!pageCache.getPageData("pledge-recharge-channel"),
  }).then((res) => {
    if (res) {
      pageData.list = res.map((e, index) => {
        e.id = index;
        e.isSelect = false;
        return e;
      });
      call(pageData.list);
    }
  });
};

const pageVisibility = usePageVisibility();
watch(pageVisibility, (value) => {
  // console.log("从后台进入前台: 刷新数据 ", value);
  if (value == "visible") {
    pageData.selectRecharge = null;
    getPledgeRechargeGearRequest(() => {
      if (route.query.taskType) {
        pageData.list.forEach((e) => {
          if (e.taskType == route.query.taskType) {
            e.isSelect = true;
            pageData.selectRecharge = e;
          } else {
            e.isSelect = false;
          }
        });
      }
    });
  }
});

onMounted(() => {
  // 1. 埋点
  firebase?.logEvent("BDC_H5_Pledge_Recharge_PUV");
  // 2. 获取列表
  pageData.selectRecharge = null;
  getPledgeRechargeGearRequest(() => {
    if (route.query.taskType) {
      pageData.list.forEach((e) => {
        if (route.query && e.taskType == route.query.taskType) {
          e.isSelect = true;
          pageData.selectRecharge = e;
        } else {
          e.isSelect = false;
        }
      });
    }
  });
  // 3. 获取保存的渠道信息
  changeChannel();
  // 4. 获取最后一次成功支付的渠道 id
  getPayEndSuccessID({ cache: true }).then((res) => {
    if (res && res.lastPayId) {
      console.log("--获取最后一次成功支付的渠道 id--", res.lastPayId);
      userState.$patch((state) => {
        state.lastPayChannelID = res.lastPayId;
      });
    }
  });
});

// 选择充值金额
const radioChannel = (val) => {
  // 1. 是否存在充值渠道,存在判断是否超过渠道充值上限,超过则需要重新选择
  if (pageData.selectChannel && pageData.selectChannel.rechargeMax) {
    if (Number(val.cash) > pageData.selectChannel.rechargeMax) {
      pageData.selectChannel = null;
      showToast(t("pledge.qxzczqd"));
    }
  }
  // 1.1 充值金额不能低于充值的下限
  if (pageData.selectChannel && pageData.selectChannel.rechargeMin) {
    if (Number(val.cash) < pageData.selectChannel.rechargeMin) {
      pageData.selectChannel = null;
      showToast(t("pledge.qxzczqd"));
    }
  }
  // 2. 选中档位
  val.isSelect = true;
  pageData.list.forEach((e) => {
    if (e.id != val.id) e.isSelect = false;
  });
  // 3. 赋值档位
  pageData.selectRecharge = val;
};

// 展示渠道选择
const showChannelView = async (isSelect) => {
  if (!pageData.selectRecharge) return showToast(t("pledge.qxzczje"));

  await navigateI18nTo({
    path: "/pledge/channel-select",
    query: {
      payId: pageData.selectChannel ? pageData.selectChannel.payId : "",
      cash: cash.value,
      sourceId: pageData.selectRecharge.taskType,
    },
  });
};

// 渠道回调
const changeChannel = () => {
  const val = pageCache.getPageData("pledge-recharge-channel");
  // console.log("--渠道--", val);
  // rechargeMax 不存在就代表没有限制
  // 1. 如果当前已选择充值金额大于当前支付方式的最大充值金额,则更换充值的档位,如果没有满足的则提示
  if (val && val?.rechargeMax && cash.value > 0) {
    if (cash.value > Number(val?.rechargeMax)) {
      // 查找小于当前支付方式最大充值金额的档位
      const findIndex = pageData.list?.findLastIndex(
        (target) => Number(target.cash) <= Number(val.rechargeMax)
      );
      // 切换选中的档位
      if (findIndex >= 0) {
        // changeDw(findIndex);
        pageData.list.forEach((e, index) => {
          if (index == findIndex) {
            e.isSelect = true;
            // 当前充值渠道最大充值 xxx 美元
            pageData.selectRecharge = e;
          } else {
            e.isSelect = false;
          }
        });
      } else {
        return showToast(t("pledge.qcxxz"));
      }
    }
  }
  // 2. 赋值选择的渠道
  if (val) pageData.selectChannel = val;
};

// 立即充值
const handleSubmit = () => {
  if (!pageData.selectRecharge) return showToast(t("pledge.qxzczje"));
  if (!pageData.selectChannel) return showToast(t("pledge.qxzczqd"));
  thirdPayApi();
};

// 唤起第三方支付
const loading = ref(false);
const thirdPayApi = debounce(
  async () => {
    // 1. 使用 loading 遮罩
    const toast = showLoadingToast({
      message: `${t("common.requestIng")}...`,
      forbidClick: true,
      duration: 15000,
    });

    try {
      if (loading.value) return;
      loading.value = true;
      // 2. 支付埋点
      firebase?.logEvent("BDC_H5_Pledge_Recharge_payment", {
        sid: (userState.$state && userState.$state.sid) || "未知sid",
        cash: cash.value,
      });
      // 3. 创建订单,并跳转支付
      const result = await thirdPay(
        {
          /****** start 自定义参数 start *******/
          // 自定义参数: 2024.04.03 [14:40] Morgan "task":null,"sourceType":4,"sourceId":取对应的任务类型
          task: null,
          sourceType: 4,
          sourceId: `${pageData.selectRecharge.taskType}`, // 取对应的任务类型
          /****** end 自定义参数 end *******/
          orderMoney: String(cash.value),
          payId: pageData.selectChannel?.payId,
          isNeedPreferential: 1,
          sourceTime: `${new Date().valueOf()}`, // 时间戳
        },
        pageData.selectChannel.requestUrl ?? "",
        globalStore.$state.packageId
      );
      toast.close();
      if (!result) {
        showToast(t("common.networkAnomaly"));
        sendCommonMessage({ message: `h5创建支付订单失败,result=null` });
      } else if (result.code === 200) {
        if (result.data && result.data?.payUrl) {
          // iOS桥接: 默认浏览器打开,如有安装手动点击跳转,没有这正常加载支付链接
          if (isiOS.value) {
            bridge.defaultBrowserOpen(result.data?.payUrl);
          }
          // 安卓桥接:打开三方 app,如果咩有安装,默认浏览器打开h5
          else {
            bridge.defaultBrowserOpen(result.data?.payUrl);
          }
        } else {
          showToast(t("common.networkAnomaly"));
          sendCommonMessage({ message: `h5创建支付订单失败,payUrl不存在` });
          MITO.log({
            message: `h5创建支付订单失败,payUrl不存在`,
            tag: "手动上报",
            level: "high",
            ex: "手动上报",
          });
        }
      } else {
        if (result.data.errors) {
          showToast(result.data.errors);
        }
        sendCommonMessage({
          message: `支付失败:档位-${JSON.stringify(
            pageData.selectRecharge
          )}渠道-${JSON.stringify(pageData.selectChannel)}错误信息-${
            result.data.errors
          }`,
        });
        MITO.log({
          message: `支付失败:档位-${JSON.stringify(
            pageData.selectRecharge
          )}渠道-${JSON.stringify(pageData.selectChannel)}错误信息-${
            result.data.errors
          }`,
          tag: "手动上报",
          level: "high",
          ex: "手动上报",
        });
      }
    } catch (error) {
      toast.close();
      sendCommonMessage({ message: `h5支付代码执行失败:${error}` });
      MITO.log({
        message: `支付代码执行失败:${error}`,
        tag: "手动上报",
        level: "high",
        ex: "手动上报",
      });
      console.log(error);
    } finally {
      loading.value = false;
      toast.close();
    }
  },
  2000,
  false
);
</script>
<style lang="scss" scoped>
.moduleView {
  position: relative;
  background-color: #fff;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  &-bg {
    background: linear-gradient(161deg, #bcdbff -16.25%, #f8f9fa 70.92%);
    background-size: 100vh 250 * 2px;
    background-repeat: no-repeat;
    margin-bottom: 70 * 2px;
  }
  .content {
    margin-top: 20 * 2px;
    padding: 0 15 * 2px;
    background-color: #fff;
    border-radius: 16 * 2px;

    &-title {
      color: #141924;
      font-size: 15 * 2px;
      font-weight: 590;
      padding-top: 20 * 2px;
      margin-bottom: 10 * 2px;
    }
    &-item {
      margin-bottom: 20 * 2px;
      justify-content: space-between;
      background-color: #fff7e3;
      border-radius: 12 * 2px;
      &-select {
        border: 3px solid #ffb800;
      }
      &-left {
        flex: 1;
        &-box {
          position: relative;
          margin-right: 10 * 2px;
        }
        &-img {
          width: 110 * 2px;
          height: 81 * 2px;
        }
        &-money {
          position: absolute;
          top: 12 * 2px;
          width: 100%;
          text-align: center;
          color: #b34b00;
          font-size: 24 * 2px;
          font-weight: 500;
        }
        &-xzcz {
          position: absolute;
          bottom: 7 * 2px;
          width: 100%;
          justify-content: center;
          &-text {
            padding: 2 * 2px 7 * 2px;
            border-radius: 100px;
            background: #ffd098; // FFDC79
            color: #b34b00; // C37A25
            font-size: 12 * 2px;
            &-normal {
              background: #ffdc79 !important; // FFDC79
              color: #c37a25 !important; // C37A25
            }
          }
        }
        &-title {
          @include multi-line-omit(2);
          min-height: 36 * 2px;
          max-height: 36 * 2px;
          color: #141924;
          font-size: 13 * 2px;
          line-height: 18 * 2px;
          margin-bottom: 12 * 2px;
          word-break: break-word;
        }
        &-rate {
          display: inline-flex !important;

          background: linear-gradient(90deg, #ffda71 0%, #fff4d4 100%);
          // background: linear-gradient(90deg, #ffdecc 0%, #fff5d8 100%);
          border-radius: 100px;
          padding: 2 * 2px 10 * 2px;

          &-img {
            width: 14 * 2px;
            height: 14 * 2px;
            margin-right: 4 * 2px;
          }
          &-text {
            color: #b34b00;
            font-size: 11 * 2px;
            font-weight: 590;
          }
        }
      }
      &-right {
        margin-right: 10 * 2px;
        border: 3px solid #d0d4df;
        border-radius: 100px;
        overflow: hidden;
        background-color: transparent !important;
        &-center {
          margin: 2 * 2px;
          border-radius: 100px;
          width: 13 * 2px;
          height: 13 * 2px;
        }
      }
    }
    &-zfqd {
      &-title {
        margin-top: 40 * 2px;
        margin-bottom: 10 * 2px;
        color: #141924;
        font-size: 15 * 2px;
        font-weight: 590;
      }

      &-channel {
        &-select {
          justify-content: space-between;
          padding: 15 * 2px 10 * 2px;
          background-color: #f8f9fa;
          border-radius: 12 * 2px;
        }
        &-list {
          justify-content: space-between;
          padding: 15 * 2px 10 * 2px;
          background-color: #f8f9fa;
          border-radius: 12 * 2px;
          &-left {
            &-img {
              position: relative;
              min-width: 40 * 2px;
              max-width: 40 * 2px;
              max-height: 40 * 2px;
              min-height: 40 * 2px;
              line-height: 24 * 2px;
              font-size: 24 * 2px;
              border: 3px solid #f8f9fa;
              background-color: #fff;
              border-radius: 8 * 2px;
              overflow: hidden;
            }
            &-title {
              color: #141924;
              margin-left: 10 * 2px;
              font-size: 15 * 2px;
              font-weight: 590;
            }
          }
          &-right {
            color: #999da7;
            font-size: 13 * 2px;
          }
        }
      }
    }
  }
  .footer {
    padding: 12 * 2px 15 * 2px;
    justify-content: space-between;
    position: fixed;
    border-top: 3px solid #e7e9e8;
    background-color: #fff;
    width: 100vw;
    bottom: var(--safe-area-inset-bottom);

    &-left {
      &-money {
        color: #232020;
        font-size: 20 * 2px;
        font-weight: 590;
        margin-bottom: 5 * 2px;
      }
      &-value {
        color: #999da7;
        font-size: 15 * 2px;
      }
    }
    &-right {
      background-color: #007bff;
      padding: 12 * 2px 17 * 2px;
      border-radius: 6 * 2px;
      color: #fff;
      font-size: 15 * 2px;
      font-weight: 510;
      &-disabled {
        background-color: #a0ceff !important;
      }
    }
  }
}
</style>
